package com.lagou.rocketmq.rocketmq;

import com.alibaba.fastjson.JSON;
import com.lagou.rocketmq.entity.Order;
import com.lagou.rocketmq.service.OrderService;
import com.lagou.rocketmq.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RocketMQMessageListener(topic = "ef-upload-video",selectorExpression="*",consumerGroup = "consumer_group_order")
public class OrderMsgListener implements RocketMQListener<MessageExt> {

    @Autowired
    private OrderService orderService;

    @Autowired
    private ProductService productService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void onMessage(MessageExt message) {
        byte[] body = message.getBody();
        String orderMsg = new String(body);
        log.info("接收到订单消息：{}", orderMsg);
        Order order = JSON.parseObject(orderMsg, Order.class);

        //检查库存
        Long stockNum = redisTemplate.opsForValue().decrement("product:stock:" + order.getProductId());
        if (stockNum >= 0) {
            //生成订单
            orderService.newOrder(order);
        } else {
            log.info("库存不够！");
        }

    }
}
